﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Android_Helper.Utils
{
    class ExcelUtils
    {
        public static Dictionary<int, string> getColumnTitle(string fileName, int sheetIndex = 0, int rowIndex = 0) {

            Dictionary<int, string> resultList = new Dictionary<int, string>();
            using (FileStream fs = File.OpenRead(fileName))
            {
                IWorkbook workbook = null;
                // 如果是2007+的Excel版本
                if (fileName.IndexOf(".xlsx") > 0)
                {
                    workbook = new XSSFWorkbook(fs);
                }
                // 如果是2003-的Excel版本
                if (fileName.IndexOf(".xls") > 0)
                {
                    workbook = new HSSFWorkbook(fs);
                }
                if (workbook == null) {
                    return resultList;
                }
                //循环读取Excel的每个sheet，每个sheet页都转换为一个DataTable，并放在DataSet中
                ISheet sheet = workbook.GetSheetAt(sheetIndex);
                int rowCount = sheet.LastRowNum;//获取总行数
                if (rowCount == 0) {
                    return resultList;
                }
                IRow firstRow = sheet.GetRow(0);//获取第一行
                int cellCount = firstRow.LastCellNum;//获取总列数
                for (int colIndex = firstRow.FirstCellNum; colIndex < cellCount; ++colIndex)
                {
                    ICell cell = firstRow.GetCell(colIndex);
                    if (cell == null)
                    {
                        continue;
                    }
                    string columnName = cell.StringCellValue;
                    if (!string.IsNullOrEmpty(columnName))
                    {
                        resultList.Add(colIndex, columnName);
                    }
                }
                
            }
            return resultList;
        }
    }
}
